﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using sql表结构对比.Model;
using System.Data.Entity.Validation;
using sql表结构对比.Repository;
using System.Data.SqlClient;
using sql表结构对比.IRepository;
using sql表结构对比.DataBusinessLayer;
using System.Data;
namespace sql表结构对比.Repository
{
    class Common
    {

        public Common()
        {

        }
        public static int allCount = 0;
        public static int curProgress = 0;
        //表数据导入
        #region
        public void Import_Booking(string OrgId, out string errorInfo)
        {

            SourTestEntities STEntity = new SourTestEntities();
            string info = string.Empty;
            int successCount = 0;
            int fatalCount = 0;
            List<wx_booking> wx_books = (from u in STEntity.wx_booking where u.OrgId.Equals(OrgId) select u).ToList();
            allCount = wx_books.Count;
            foreach (var item in wx_books)
            {
                curProgress++;
                DesTestEntities DTEentity = new DesTestEntities();
                hos_booking hos_book = new hos_booking();
                hos_book.org_id = item.OrgId.Trim();
                hos_book.pat_id = item.PatientId;
                hos_book.bk_doctCode = item.DoctorCode;
                hos_book.bk_doctName = item.DoctorName;
                hos_book.bk_scheduleId = item.ScheduleId;
                hos_book.bk_adviceTime = item.AdviceTime;
                hos_book.pat_name = item.PatientName;
                hos_book.pat_visitingCard = item.VisitingCard;
                hos_book.bk_regid = item.RegId;
                hos_book.bk_deptCode = item.DeptCode;
                hos_book.bk_deptName = item.DeptName;
                hos_book.bk_clinicCode = item.ClinicCode;
                hos_book.bk_clinicName = item.ClinicName;
                hos_book.bk_clinicFee = item.ClinicFee;
                hos_book.bk_queueSn = item.QueueSn;
                hos_book.bk_mobile = item.BookMobile;
                hos_book.bk_status = int.Parse(item.Status);
                hos_book.bk_date = item.BookDate;
                hos_book.vis_id = item.VisitingId;
                hos_book.vis_times = item.Times;
                hos_book.vis_pay_flag = item.PayIsDone;
                hos_book.bk_roomNo = item.RoomNo;
                hos_book.bk_visitingSpan = item.VisitingSpan;

                try
                {
                    DTEentity.hos_booking.Add(hos_book);
                    DTEentity.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    StringBuilder errors = new StringBuilder();
                    IEnumerable<DbEntityValidationResult> validationResult = ex.EntityValidationErrors;
                    foreach (DbEntityValidationResult result in validationResult)
                    {
                        ICollection<DbValidationError> validationError = result.ValidationErrors;
                        foreach (DbValidationError err in validationError)
                        {
                            errors.Append("BookingSn=" + item.BookingSn + "导入失败！ 理由:" + err.PropertyName + ":" + err.ErrorMessage + "\r\n");
                            fatalCount++;
                            info += errors.ToString();
                        }
                    }

                }
            }
            successCount = allCount - fatalCount;
            if (info == "")
            {
                errorInfo = "共" + successCount.ToString() + "条数据全部导入成功！";
            }
            else
            {
                errorInfo = info + "\r\n" + "成功导入:" + successCount.ToString() + "条" + " 导入失败:" + fatalCount.ToString() + "条";
            }
        }
        public void Import_Dept(string OrgId, out string errorInfo)
        {
            SourTestEntities STEntity = new SourTestEntities();
            List<wx_dict_dept> wx_depts = (from u in STEntity.wx_dict_dept where u.OrgId.Equals(OrgId) select u).ToList();
            deptRepository deptRP = new deptRepository();
            string info = string.Empty;
            int successCount = 0;
            int fatalCount = 0;
            allCount = wx_depts.Count;
            foreach (var item in wx_depts)
            {
                curProgress++;
                DesTestEntities DTEentity = new DesTestEntities();
                hos_dic_dept dic_dept = new hos_dic_dept();
                dic_dept.dept_id = deptRP.GetNewDept_id();
                dic_dept.org_id = item.OrgId;
                dic_dept.dept_code = item.DeptCode;
                dic_dept.dept_name = item.DeptName;
                dic_dept.dept_address = item.DeptAddress;
                dic_dept.dept_intro = item.Intro;
                dic_dept.dept_type = item.DeptType.Trim();
                dic_dept.dept_photo = item.Photo;
                dic_dept.dept_thumb = item.Thumb;
                dic_dept.par_dept_code = item.ParentSn;
                dic_dept.intro_rank = item.IntroRank;
                dic_dept.bk_rank = item.BookingRank;
                try
                {
                    DTEentity.hos_dic_dept.Add(dic_dept);
                    DTEentity.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    StringBuilder errors = new StringBuilder();
                    IEnumerable<DbEntityValidationResult> validationResult = ex.EntityValidationErrors;
                    foreach (DbEntityValidationResult result in validationResult)
                    {
                        ICollection<DbValidationError> validationError = result.ValidationErrors;
                        foreach (DbValidationError err in validationError)
                        {
                            errors.Append("DeptSn=" + item.DeptSn.ToString() + "导入失败！ 理由:" + err.PropertyName + ":" + err.ErrorMessage + "\r\n");
                            fatalCount++;
                            info += errors.ToString();
                        }
                    }

                }
            }
            successCount = allCount - fatalCount;

            if (info == "")
            {
                errorInfo = "共" + successCount.ToString() + "条数据全部导入成功！";
            }
            else
            {
                errorInfo = info + "\r\n" + "成功导入:" + successCount.ToString() + "条" + " 导入失败:" + fatalCount.ToString() + "条";
            }

        }
        public void Import_Doctor(string OrgId, out string errorInfo)
        {
            SourTestEntities STEntity = new SourTestEntities();
            List<wx_dict_doctor> wx_doctors = (from u in STEntity.wx_dict_doctor where u.OrgId.Equals(OrgId) select u).ToList();
            doctorRepository doctRP = new doctorRepository();
            string info = string.Empty;
            int successCount = 0;
            int fatalCount = 0;
            allCount = wx_doctors.Count;
            foreach (var item in wx_doctors)
            {
                curProgress++;
                DesTestEntities DTEentity = new DesTestEntities();
                hos_dic_doctor dic_doctor = new hos_dic_doctor();
                dic_doctor.doct_code = item.DoctorCode;
                dic_doctor.doct_name = item.DoctorName;
                dic_doctor.doct_title = item.JobTitleName;
                dic_doctor.doct_intro = item.Introdution;
                dic_doctor.doct_photo = item.Photo;
                dic_doctor.doct_thumb = item.Thumb;
                dic_doctor.doct_type = item.DoctType.Trim();
                dic_doctor.intro_sort_no = item.IntroRank;
                dic_doctor.book_sort_no = item.BookingRank;
                dic_doctor.org_id = item.OrgId.Trim();
                dic_doctor.dept_code = item.DeptCode;
                wx_dict_dept dept = doctRP.GetDept(item.DeptCode);
                if (dept == null)
                {
                    dic_doctor.dept_name = "";
                }
                else
                {
                    dic_doctor.dept_name = dept.DeptName;
                }

                dic_doctor.sec_dept_code = item.SecDeptCode;
                dic_doctor.doct_forte = item.Advantage;
                try
                {
                    DTEentity.hos_dic_doctor.Add(dic_doctor);
                    DTEentity.SaveChanges();
                }
                catch (System.Data.Entity.Validation.DbEntityValidationException ex)
                {
                    StringBuilder errors = new StringBuilder();
                    IEnumerable<DbEntityValidationResult> validationResult = ex.EntityValidationErrors;
                    foreach (DbEntityValidationResult result in validationResult)
                    {
                        ICollection<DbValidationError> validationError = result.ValidationErrors;
                        foreach (DbValidationError err in validationError)
                        {
                            errors.Append("DoctorSn=" + item.DoctorSn.ToString() + "导入失败！ 理由:" + err.PropertyName + ":" + err.ErrorMessage + "\r\n");
                            fatalCount++;
                            info += errors.ToString();
                        }
                    }

                }
            }
            successCount = allCount - fatalCount;

            if (info == "")
            {
                errorInfo = "共" + successCount.ToString() + "条数据全部导入成功！";
            }
            else
            {
                errorInfo = info + "\r\n" + "成功导入:" + successCount.ToString() + "条" + " 导入失败:" + fatalCount.ToString() + "条";
            }

        }
        #endregion

        //源表和目的表下拉框绑定
        public void BindTable(string InputStr, List<string> basicinfo, out string OutputStr)
        {

            tb_Dictionary tbD = new tb_Dictionary(basicinfo);
            if (tbD.tb_dic.ContainsKey(InputStr))
            {
                OutputStr = tbD.tb_dic[InputStr];
            }
            else
            {
                OutputStr = "没有对应的表";
            }
            if (tbD.tb_dic.ContainsValue(InputStr))
            {
                foreach (var item in tbD.tb_dic.Keys)
                {
                    if (tbD.tb_dic[item] == InputStr)
                    {
                        OutputStr = item;
                        break;
                    }
                }
            }

        }
      
        //获取表字段名和类型及长度
        #region
        public DataTable Getinfo(string tablename, string connstr, out string error)
        {
            string cmd = "SELECT  字段名     = a.name,   类型       = b.name,   长度       = COLUMNPROPERTY(a.id,a.name,'PRECISION') FROM syscolumns a left join systypes b on a.xusertype=b.xusertype inner join sysobjects d on  a.id=d.id  and d.xtype='U' and  d.name<>'dtproperties' left join syscomments e on a.cdefault=e.id where  d.name='" + tablename + "' order by  a.id,a.colorder ";

            return SqlHelper.GetTable(cmd, connstr, out error);
        }
          //取出存在关系的那一行的字段信息
        public DataRow Getfieldrecord(DataTable t,string str) {
            DataRow result = t.NewRow();
            for (int i = 0; i < t.Rows.Count; i++)
            {
                if (str == t.Rows[i][0].ToString()) {
                    result = t.Rows[i];
                    break;
                }
            }
            return result;
        }
        public List<DataTable> GetfieldInfo(DataTable dt_s, DataTable dt_d, List<string> basicinfo)
        {
            tablerelationship relationship = (new DedicatedService()).comfirm(basicinfo);
            List<DataTable> tables = new List<DataTable>();
            DataTable temp_s = dt_s.Clone();
            DataTable temp_d = dt_d.Clone();
            if (relationship == null)
            {
                return null;
            }
            else
            {
                foreach (string  item in relationship.filedRelationship)
                {
                    string[] str= item.Split(new char[] { '-', '>' });
                    temp_s.ImportRow(Getfieldrecord(dt_s,str[0]));
                    temp_d.ImportRow(Getfieldrecord(dt_d, str[2]));
                }
                tables.Add(temp_s);
                tables.Add(temp_d);
                return tables;
            }
          
          

        }
        #endregion


        //错误补充
        #region
        //public string error1(DataTable dt_S,DataTable dt_D) {
        //    //string result = "源表"+"             "+"目的表"+"\r\n";
        //    //for (int i = 0; i < s.Count; i++)
        //    //{
        //    //    result += s[i].fieldName + "    " + s[i].type + "   " + s[i].lenth + "                 " + d[i].fieldName + "" + d[i].type + "" + d[i].lenth+"\r\n";
        //    //}
        //    //return result;


        //}

        public string ErrorSet(int errorcode, out string errorinfo)
        {
            switch (errorcode)
            {
                case 1: break;
                case 2: break;
                case 3: break;
                default:
                    break;
            }
            errorinfo = "";
            return null;
        }
        #endregion

        //获取导入excel数据前的配置信息
        public string GetExcelConfig(string[] str)
        {
            string config = "server=";
            config += str[0] + ";uid=";
            config += str[1] + ";pwd=";
            config += str[2] + ";database=";
            return config;
        }
    }
}
